package com.tanklab.signature.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Configuration
public class FileStorageConfig implements WebMvcConfigurer {

    @Value("${avatar.upload-dir}")
    private String avatarUploadDir;

    @Value("${avatar.access-path}")
    private String avatarAccessPath;

    @Value("${file.upload-dir:./uploads/files/}")
    private String fileUploadDir;

    @Value("${file.access-path:/files/}")
    private String fileAccessPath;

    @Value("${signature.upload-dir:./uploads/signatures/}")
    private String signatureUploadDir;

    @Value("${signature.access-path:/signatures/}")
    private String signatureAccessPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 确保头像目录存在
        File avatarDir = new File(avatarUploadDir);
        if (!avatarDir.exists()) {
            avatarDir.mkdirs();
        }

        // 确保文件上传目录存在
        File fileDir = new File(fileUploadDir);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        // 确保签名图片目录存在
        File signatureDir = new File(signatureUploadDir);
        if (!signatureDir.exists()) {
            signatureDir.mkdirs();
        }

        // 添加头像资源处理器
        registry.addResourceHandler(avatarAccessPath + "/**")
                .addResourceLocations("file:" + avatarUploadDir);

        // 添加文件资源处理器
        registry.addResourceHandler(fileAccessPath + "/**")
                .addResourceLocations("file:" + fileUploadDir);

        // 添加签名图片资源处理器
        registry.addResourceHandler(signatureAccessPath + "/**")
                .addResourceLocations("file:" + signatureUploadDir);
    }
}